<script lang="ts" setup name="productExchangeEdit">
import { ref, reactive, onMounted } from "vue";
import { ExchangeList } from "@/types/createActivity";
import { ElForm, ElTable } from "element-plus";
import HeaderCard from "./components/HeaderCard.vue";
import { useRoute, useRouter } from "vue-router";
import SelectTreeData from "@/components/SelectTreeData/index.vue";
import { getGoodsList, getFoodCategoryList } from "@/api/modules/goods";
import { createExchangeProductAPI, getExchangeDetailAPI, editExchangeDetailAPI } from "@/api/modules/activity";
import { default as Sortable, SortableEvent } from "sortablejs";
import { getDateNow } from "@/utils/date";
const router = useRouter();
const route = useRoute();

const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const exchangeList = ref<ExchangeList>({
  id: 0,
  name: "",
  path: "/marketing/product-exchange?id=",
  code: "",
  type: 7, // 超值换购
  desc: "",
  rule: {
    conditionType: 1, // 1按金额 2按数量
    conditionValue: "", // 条件值
    selectType: 1, // 1.任意 2.指定菜品
    selectIds: [], // 选定id
    inCreaseList: [] // {} 每个促销对象的id数量自填价格自填
  },
  cycleType: 0, // 可用周期( 0.每天；1.周（周一至周日);2.月（1-31号）)
  cycleValue: [], // 选择周或者那一天的数组
  validityRange: [getDateNow(0), getDateNow(1)], // 日期
  promotionType: 2 // 1.营销活动 2.餐饮促销活动 先写死2
});
const rules = {
  name: [{ required: true, message: "请输入活动名称" }],
  cycleValue: [{ required: true, message: "请选择可用周期" }],
  validityRange: [{ required: true, message: "请选择可用日期" }],
  "rule.conditionValue": [
    { required: true, message: "请输入" },
    {
      validator(rule: any, value: any[], callback: Function) {
        if (isNaN(Number(exchangeList.value.rule.conditionValue))) {
          callback(new Error("请输入正确的值"));
        }
        callback();
      }
    }
  ],
  "rule.selectIds": [
    {
      validator(rule: any, value: any[], callback: Function) {
        if (exchangeList.value.rule.selectType === 2 && exchangeList.value.rule.selectIds.length < 1) {
          callback(new Error("请选择适用菜品"));
        }
        callback();
      }
    }
  ],
  "rule.inCreaseList": [
    { required: true, message: "请选择活动菜品" },
    {
      validator(rule: any, value: any[], callback: Function) {
        if (
          exchangeList.value.rule.inCreaseList.some(v => isNaN(Number(v.activityPrice))) ||
          // exchangeList.value.rule.inCreaseList.some(v => !v.activityPrice) ||
          exchangeList.value.rule.inCreaseList.some(v => !v.limit)
        ) {
          callback(new Error("请输入正确的值"));
        }
        callback();
      }
    }
  ]
};
const cycleData = reactive([
  { label: "星期一", value: 1 },
  { label: "星期二", value: 2 },
  { label: "星期三", value: 3 },
  { label: "星期四", value: 4 },
  { label: "星期五", value: 5 },
  { label: "星期六", value: 6 },
  { label: "星期日", value: 7 }
]);
// 切换可用日期
const onChangeCycleType = () => {
  exchangeList.value.cycleValue = [];
};
const onChangeActivityMethod = () => {
  // 修改按金额还是按数量
  exchangeList.value.rule.selectIds = [];
  exchangeList.value.rule.selectType = 1;
  commonProductList.value = [];
};
const onChangeExpense = () => {
  // 修改任意菜还是活动菜
  exchangeList.value.rule.selectIds = [];
  commonProductList.value = [];
};
// 选择菜
const commonProductList = ref<any[]>([]);
const SelectTreeRef = ref<InstanceType<typeof SelectTreeData> | null>(null);
const openSelectTreeData = (index: number, type: string) => {
  SelectTreeRef.value?.acceptParams({
    title: "选择菜品",
    columns: [
      { type: "selection", label: "#", width: 60 },
      { prop: "name", label: "菜品名称", align: "left" },
      { prop: "foodSpecName", label: "量", align: "left" },
      { prop: "foodTypeName", label: "分类", align: "left" }
    ],
    idName: "foodCategoryId",
    isView: false,
    index,
    type,
    mate: "foodSpecId",
    selTags:
      type === "commonProduct"
        ? commonProductList.value.map(v => {
            v.id = v.foodSpecId;
            v.name = v.name;
            return v;
          })
        : exchangeList.value.rule.inCreaseList.map(v => {
            v.id = v.foodSpecId;
            v.name = v.name;
            return v;
          }),
    api: getGoodsList,
    treeApi: getFoodCategoryList
  });
};
interface SelectList {
  list: any[];
  title: string;
  index: number;
  type: string;
}
/*
  1.处理id加入rule。valueIds中
  2.处理切换消费方式时清空数组
*/
// 选中数量
const onselectList = (e: SelectList) => {
  e.type === "commonProduct"
    ? (commonProductList.value = JSON.parse(JSON.stringify(e.list)))
    : (exchangeList.value.rule.inCreaseList = e.list.map((i, index) => {
        return {
          activityPrice: 1,
          limit: 1,
          sort: index,
          ...i
        };
      }));
  rowDrag();
  if (e.type === "commonProduct") {
    exchangeList.value.rule.selectIds = e.list.map(v => v.foodSpecId);
    formRef.value?.validateField("rule.selectIds");
  }
};
// 删除数据
const oncloseCommon = (index: number, type: string) => {
  type === "commonProduct" ? commonProductList.value.splice(index, 1) : exchangeList.value.rule.inCreaseList?.splice(index, 1);

  if (type === "commonProduct") {
    exchangeList.value.rule.selectIds.splice(index, 1);
  }
};

// 获取单条数据详细
const getExchangeDetail = async () => {
  const res: any = await getExchangeDetailAPI({ id: route.query.id });
  commonProductList.value = res.data.rule.selectList;
  Object.keys(exchangeList.value).forEach(key => {
    if (res.data.hasOwnProperty(key)) {
      exchangeList.value[key] = res.data[key];
    }
  });
  exchangeList.value.rule = JSON.parse(JSON.stringify(res.data.rule));
};
// 编辑数据
onMounted(async () => {
  if (route.query.id) {
    await getExchangeDetail();
  }
  rowDrag();
});

// 提交数据
const onSubmit = async () => {
  await formRef.value?.validate();
  if (route.query.id) {
    await editExchangeDetailAPI(exchangeList.value);
  } else {
    await createExchangeProductAPI({
      ...JSON.parse(JSON.stringify(exchangeList.value)),
      inCreaseList: exchangeList.value.rule.inCreaseList.map((i, index) => {
        return {
          foodSpecId: i.foodSpecId,
          activityPrice: i.activityPrice,
          limit: i.limit,
          sort: index + 1,
          id: i.foodSpecId,
          name: i.name
        };
      })
    });
  }
  router.push("/marketing/coupon-scan?upList=" + true);
};

// 拖拽表格的行
const tableRef = ref<InstanceType<typeof ElTable> | null>(null);
// 行拖拽
const rowDrag = function () {
  // 要拖拽元素的父容器
  const tbody = document.querySelector(".draggable .el-table__body-wrapper tbody");
  if (!tbody) return;
  Sortable.create(tbody as HTMLElement, {
    //  可被拖拽的子元素
    draggable: ".draggable .el-table__row",
    onEnd(event: SortableEvent) {
      if (event.oldIndex !== undefined && event.newIndex !== undefined) {
        const currRow = exchangeList.value.rule.inCreaseList.splice(event.oldIndex, 1)[0];
        exchangeList.value.rule.inCreaseList.splice(event.newIndex, 0, currRow);
      }
    }
  });
};
</script>

<template>
  <div class="exchange-container">
    <HeaderCard
      @back="router.back()"
      :title="(route.query.id ? '编辑' : '新增') + '超值换购活动'"
      @confirm="onSubmit"
      :is-show-button="route.query.type === 'view' ? false : true"
    ></HeaderCard>
    <div class="main">
      <el-row class="h">
        <el-col style="height: 100%; padding: 20px; overflow: hidden" :span="5">
          <img style="width: 96%; height: 92%" src="@/assets/images/exchange.png" alt="" />
        </el-col>
        <el-col class="h" :span="19">
          <div style="width: 100%; height: 96%; overflow-y: auto">
            <el-form
              label-width="120"
              ref="formRef"
              style="width: 50%; height: 96%; padding: 20px"
              :model="exchangeList"
              :rules="rules"
            >
              <div>活动基础信息</div>
              <div class="content">
                <el-form-item label="活动名称：" prop="name">
                  <el-input v-model="exchangeList.name"></el-input>
                </el-form-item>
                <!-- <el-form-item label="活动标题：">
          <el-input></el-input>
        </el-form-item>
        <el-form-item label="活动标签：">
          <el-input></el-input>
        </el-form-item> -->
                <el-form-item label="活动编码：" prop="code">
                  <el-input v-model="exchangeList.code"></el-input>
                </el-form-item>

                <!-- <el-form-item label="活动日期">
          <el-radio-group @change="onChangeCycleType">
            <el-radio :value="0" size="large">永久有效</el-radio>
            <el-radio :value="1" size="large">自定义时间</el-radio>
          </el-radio-group>
        </el-form-item> -->
                <el-form-item label="自定义日期" prop="validityRange">
                  <el-date-picker
                    v-model="exchangeList.validityRange"
                    format="YYYY-MM-DD"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                  />
                </el-form-item>
                <el-form-item label="可用周期" prop="cycleType">
                  <el-radio-group v-model="exchangeList.cycleType" @change="onChangeCycleType">
                    <el-radio :value="0" size="large">每天</el-radio>
                    <el-radio :value="1" size="large">每周</el-radio>
                    <el-radio :value="2" size="large">每月</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  label=""
                  prop="cycleValue"
                  v-if="exchangeList.cycleType === 1"
                  :rules="exchangeList.cycleType === 1 ? rules.cycleValue : [{ required: false }]"
                >
                  <div class="select-day-in-week-wrapper">
                    <el-checkbox-group v-model="exchangeList.cycleValue">
                      <el-checkbox v-for="cycle in cycleData" :key="cycle.value" :value="cycle.value">{{
                        cycle.label
                      }}</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </el-form-item>
                <el-form-item
                  label=""
                  prop="cycleValue"
                  v-if="exchangeList.cycleType === 2"
                  :rules="exchangeList.cycleType === 2 ? rules.cycleValue : [{ required: false }]"
                >
                  <div class="select-day-in-week-wrapper">
                    <el-checkbox-group v-model="exchangeList.cycleValue">
                      <el-checkbox v-for="day in 31" :key="'day' + day" :value="day">{{
                        day < 10 ? "0" + day : day
                      }}</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </el-form-item>

                <!-- <el-form-item label="可用时间段">
          <el-radio-group>
            <el-radio :value="0" size="large">全天</el-radio>
            <el-radio :value="1" size="large">指定时间段</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="true" style="width: 70%">
          <el-date-picker type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item> -->
              </div>

              <div class="title">活动规则</div>
              <div class="content">
                <el-form-item label="活动方式">
                  <div>活动方式任意或指定消费满一定金额或数量后，再加价一定金额即可换购指定菜品</div>
                </el-form-item>
                <el-form-item>
                  <el-radio-group v-model="exchangeList.rule.conditionType" @change="onChangeActivityMethod">
                    <el-radio :value="1" size="large">按金额</el-radio>
                    <el-radio :value="2" size="large">按数量</el-radio>
                  </el-radio-group>
                </el-form-item>
                <!-- 按金额，切换时候记得把数据清空 -->
                <el-form-item style="width: 70%" prop="rule.conditionValue">
                  <el-input
                    v-model="exchangeList.rule.conditionValue"
                    style="max-width: 600px"
                    :placeholder="+exchangeList.rule.conditionType === 1 ? '请输入价格' : '请输入数量'"
                    class="input-with-select"
                  >
                    <template #prepend>
                      <el-select @change="onChangeExpense" v-model="exchangeList.rule.selectType" style="width: 180px">
                        <el-option
                          :label="exchangeList.rule.conditionType === 1 ? '任意菜品消费满' : '任意菜品数量满'"
                          :value="1"
                        />
                        <el-option
                          :label="exchangeList.rule.conditionType === 1 ? '活动菜品消费满' : '活动菜品消费满'"
                          :value="2"
                        />
                      </el-select>
                    </template>
                    <template #append>
                      <div>{{ exchangeList.rule.conditionType === 1 ? "元" : "份" }}</div>
                    </template>
                  </el-input>
                </el-form-item>
                <!-- 按数量，切换时候记得把数据清空 -->

                <!-- 按金额显示 -->
                <!-- <el-form-item>
          <el-radio-group>
            <el-radio :value="0" size="large">按分类</el-radio> 暂无按分类，后期加
            <el-radio :value="1" size="large">按菜品</el-radio>
          </el-radio-group>
        </el-form-item> -->
                <!--
         <el-form-item label="适用菜品分类"> </el-form-item> 
         <el-form-item label="排除菜品"> </el-form-item> 
         -->
                <el-form-item prop="rule.selectIds" v-if="exchangeList.rule.selectType === 2" label="适用菜品">
                  <div class="choose-product">
                    <div class="before" v-if="commonProductList.length < 1">
                      <img src="/src/assets/icons/add.svg" alt="" @click="openSelectTreeData(0, 'commonProduct')" />
                    </div>
                    <div class="after" v-else>
                      <el-tag
                        style="margin-left: 5px"
                        type="info"
                        v-for="(tag, index) in commonProductList"
                        :key="tag.id"
                        closable
                        @close="oncloseCommon(index, 'commonProduct')"
                      >
                        {{ tag.name }}
                      </el-tag>
                    </div>
                  </div>
                  <div style="margin-left: 10px" v-if="commonProductList.length > 0">
                    <img
                      style="width: 25px; height: 25px"
                      src="/src/assets/icons/add.svg"
                      alt=""
                      @click="openSelectTreeData(0, 'commonProduct')"
                    />
                  </div>
                </el-form-item>

                <el-form-item label="活动菜品">
                  <div style="display: flex; justify-content: space-between; width: 80%">
                    <div style="font-size: 14px; color: #b0abb2">（以下活动菜品用户可任选其一参与换购）</div>
                    <div style="color: #fdb44e" @click="openSelectTreeData(1, 'activityProduct')">+增加活动菜</div>
                  </div>
                </el-form-item>

                <el-form-item prop="rule.inCreaseList">
                  <el-table
                    style="width: 600px; height: 200px; overflow: auto"
                    :data="exchangeList.rule.inCreaseList"
                    border
                    :header-cell-style="{ backgroundColor: '#f5f7fa' }"
                    row-key="id"
                    ref="tableRef"
                    class="draggable"
                  >
                    <el-table-column label="序号" width="60px">
                      <template #default="{ $index }">
                        {{ $index }}
                      </template>
                    </el-table-column>
                    <el-table-column label="菜品" prop="name" width="140px"></el-table-column>
                    <!-- <el-table-column label="单位" prop=""></el-table-column> -->
                    <el-table-column label="活动价" prop="activityPrice" width="110">
                      <template #default="{ $index }">
                        <el-input-number
                          style="width: 80%"
                          :controls="false"
                          :min="0"
                          size="small"
                          v-model="exchangeList.rule.inCreaseList[$index].activityPrice"
                        ></el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column label="最大换购数量" width="120" prop="limit">
                      <template #default="{ $index }">
                        <el-input-number
                          style="width: 80%"
                          :controls="false"
                          :min="1"
                          size="small"
                          v-model="exchangeList.rule.inCreaseList[$index].limit"
                        ></el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="70px">
                      <template #default="{ $index }">
                        <el-button type="text" @click="oncloseCommon($index, 'activityProduct')">删除</el-button>
                      </template>
                    </el-table-column>
                    <el-table-column label="分类" prop="foodSpecName" width="80px"></el-table-column>
                    <el-table-column label="售价" prop="posPrice"></el-table-column>
                    <el-table-column label="更换顺序" align="center" width="100">
                      <template #default="{}">
                        <el-icon class="drag-handler"><Rank /></el-icon>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
              </div>
            </el-form>
          </div>
        </el-col>
      </el-row>

      <SelectTreeData ref="SelectTreeRef" @selected-list="onselectList"></SelectTreeData>
    </div>
  </div>
</template>

<style lang="scss" scoped>
div {
  box-sizing: border-box;
}
.exchange-container {
  height: 100%;
  overflow: hidden;
  background-color: #ffffff;
  .main {
    height: calc(100% - 72px);
    overflow: hidden;
    .title {
      padding-top: 10px;
    }
    .content {
      padding-top: 20px;
    }
    .choose-product {
      width: 70%;
      height: 70px;
      overflow-y: auto;
      border: 1px solid #e7e7e7;
      border-radius: 5px;
      .before {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        img {
          width: 30px;
          height: 30px;
          padding-top: 5px;
        }
      }
    }
  }
}
.drag-handler {
  cursor: move;
}
.h {
  height: 100%;
}
</style>
